package com.bh.common.utils.pdf;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.PdfCopy;
import com.itextpdf.text.pdf.PdfImportedPage;
import com.itextpdf.text.pdf.PdfReader;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

/**
 * 合并pdf文件
 *
 * @author shuangluxing@163.com
 * @date 2023/03/28
 */
public class MergePdfFile {
    private static void mergePdfFiles1(List<byte[]> bytes, String newFile) {
        try {
            Document document = new Document(new PdfReader(bytes.get(1)).getPageSize(1));
            PdfCopy copy = new PdfCopy(document, new FileOutputStream(newFile));
            document.open();
            for (byte[] aByte : bytes) {
                PdfReader reader = new PdfReader(aByte);
                int n = reader.getNumberOfPages();
                for (int j = 1; j <= n; j++) {
                    document.newPage();
                    PdfImportedPage page = copy.getImportedPage(reader, j);
                    copy.addPage(page);
                }
            }
            document.close();
        } catch (IOException | DocumentException e) {
            e.printStackTrace();
        }
    }
}

